package com.demo.accessibilitykeeper;

import android.app.Service;
import android.content.Intent;
import android.os.Build;
import android.os.IBinder;
import android.util.Log;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityNodeInfo;
import android.widget.Toast;

/**
 * 投屏服务
 * 功能：在Android 14以上系统自动点击"允许"开启投屏权限
 */
public class ScreenCastService extends Service {
    private static final String TAG = "ScreenCastService";
    
    private boolean isScreenCastEnabled = false;
    private boolean isAutoClickEnabled = false;
    
    @Override
    public void onCreate() {
        super.onCreate();
        Log.d(TAG, "ScreenCastService created");
    }
    
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        String action = intent != null ? intent.getStringExtra("action") : null;
        
        if ("enable_screen_cast".equals(action)) {
            enableScreenCast();
        } else if ("disable_screen_cast".equals(action)) {
            disableScreenCast();
        } else if ("toggle_screen_cast".equals(action)) {
            toggleScreenCast();
        } else if ("auto_click_allow".equals(action)) {
            enableAutoClickAllow();
        } else if ("disable_auto_click".equals(action)) {
            disableAutoClickAllow();
        }
        
        return START_STICKY;
    }
    
    /**
     * 启用投屏
     */
    public void enableScreenCast() {
        if (isScreenCastEnabled) {
            Log.d(TAG, "Screen cast already enabled");
            return;
        }
        
        try {
            Log.d(TAG, "📺 ENABLING_SCREEN_CAST - Starting screen cast process");
            
            // 检查Android版本
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
                Log.d(TAG, "✅ Android 14+ detected, screen cast features available");
                
                // 启用自动点击允许功能
                enableAutoClickAllow();
                
                // 启动投屏相关功能
                startScreenCastFeatures();
                
            } else {
                Log.w(TAG, "⚠️ Android version below 14, limited screen cast features");
                startScreenCastFeatures();
            }
            
            isScreenCastEnabled = true;
            
            Log.d(TAG, "✅ SCREEN_CAST_ENABLED_SUCCESSFULLY");
            Toast.makeText(this, "投屏功能已启用，将自动点击允许权限", Toast.LENGTH_SHORT).show();
            
        } catch (Exception e) {
            Log.e(TAG, "❌ FAILED_TO_ENABLE_SCREEN_CAST", e);
            Toast.makeText(this, "启用投屏失败: " + e.getMessage(), Toast.LENGTH_LONG).show();
        }
    }
    
    /**
     * 禁用投屏
     */
    public void disableScreenCast() {
        if (!isScreenCastEnabled) {
            Log.d(TAG, "Screen cast not enabled");
            return;
        }
        
        try {
            Log.d(TAG, "📺 DISABLING_SCREEN_CAST - Stopping screen cast process");
            
            // 禁用自动点击允许功能
            disableAutoClickAllow();
            
            // 停止投屏相关功能
            stopScreenCastFeatures();
            
            isScreenCastEnabled = false;
            
            Log.d(TAG, "✅ SCREEN_CAST_DISABLED_SUCCESSFULLY");
            Toast.makeText(this, "投屏功能已禁用", Toast.LENGTH_SHORT).show();
            
        } catch (Exception e) {
            Log.e(TAG, "❌ FAILED_TO_DISABLE_SCREEN_CAST", e);
            Toast.makeText(this, "禁用投屏失败: " + e.getMessage(), Toast.LENGTH_LONG).show();
        }
    }
    
    /**
     * 切换投屏状态
     */
    public void toggleScreenCast() {
        if (isScreenCastEnabled) {
            disableScreenCast();
        } else {
            enableScreenCast();
        }
    }
    
    /**
     * 启用自动点击允许功能
     */
    public void enableAutoClickAllow() {
        try {
            Log.d(TAG, "🔧 ENABLING_AUTO_CLICK_ALLOW");
            
            isAutoClickEnabled = true;
            
            Log.d(TAG, "✅ AUTO_CLICK_ALLOW_ENABLED");
            Toast.makeText(this, "自动点击允许功能已启用", Toast.LENGTH_SHORT).show();
            
        } catch (Exception e) {
            Log.e(TAG, "❌ ERROR_ENABLING_AUTO_CLICK_ALLOW", e);
        }
    }
    
    /**
     * 禁用自动点击允许功能
     */
    public void disableAutoClickAllow() {
        try {
            Log.d(TAG, "🔧 DISABLING_AUTO_CLICK_ALLOW");
            
            isAutoClickEnabled = false;
            
            Log.d(TAG, "✅ AUTO_CLICK_ALLOW_DISABLED");
            Toast.makeText(this, "自动点击允许功能已禁用", Toast.LENGTH_SHORT).show();
            
        } catch (Exception e) {
            Log.e(TAG, "❌ ERROR_DISABLING_AUTO_CLICK_ALLOW", e);
        }
    }
    
    /**
     * 启动投屏相关功能
     */
    private void startScreenCastFeatures() {
        try {
            Log.d(TAG, "🔧 STARTING_SCREEN_CAST_FEATURES");
            
            // 这里可以添加投屏相关的功能
            // 例如：启动投屏、配置投屏参数等
            
            Log.d(TAG, "✅ Screen cast features started");
            
        } catch (Exception e) {
            Log.e(TAG, "❌ ERROR_STARTING_SCREEN_CAST_FEATURES", e);
        }
    }
    
    /**
     * 停止投屏相关功能
     */
    private void stopScreenCastFeatures() {
        try {
            Log.d(TAG, "🔧 STOPPING_SCREEN_CAST_FEATURES");
            
            // 这里可以添加停止投屏相关的功能
            
            Log.d(TAG, "✅ Screen cast features stopped");
            
        } catch (Exception e) {
            Log.e(TAG, "❌ ERROR_STOPPING_SCREEN_CAST_FEATURES", e);
        }
    }
    
    /**
     * 处理无障碍事件 - 自动点击允许按钮
     */
    public void handleAccessibilityEvent(AccessibilityEvent event) {
        if (!isAutoClickEnabled) {
            return;
        }
        
        try {
            // 检查是否是投屏权限对话框
            if (isScreenCastPermissionDialog(event)) {
                Log.d(TAG, "📺 SCREEN_CAST_PERMISSION_DIALOG_DETECTED");
                
                // 自动点击允许按钮
                autoClickAllowButton(event);
            }
            
        } catch (Exception e) {
            Log.e(TAG, "❌ ERROR_HANDLING_ACCESSIBILITY_EVENT", e);
        }
    }
    
    /**
     * 检查是否是投屏权限对话框
     */
    private boolean isScreenCastPermissionDialog(AccessibilityEvent event) {
        try {
            if (event.getEventType() == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED) {
                CharSequence packageName = event.getPackageName();
                CharSequence className = event.getClassName();
                
                // 检查是否是系统设置或投屏相关的对话框
                if (packageName != null && className != null) {
                    String packageNameStr = packageName.toString();
                    String classNameStr = className.toString();
                    
                    Log.d(TAG, "Checking dialog: " + packageNameStr + " / " + classNameStr);
                    
                    // 检查是否是系统设置相关的对话框
                    if (packageNameStr.contains("android") || 
                        packageNameStr.contains("settings") ||
                        packageNameStr.contains("systemui")) {
                        
                        // 检查是否包含投屏相关的文本
                        if (classNameStr.contains("Dialog") || 
                            classNameStr.contains("AlertDialog") ||
                            classNameStr.contains("Permission")) {
                            
                            Log.d(TAG, "✅ Screen cast permission dialog detected");
                            return true;
                        }
                    }
                }
            }
            
            return false;
            
        } catch (Exception e) {
            Log.e(TAG, "❌ ERROR_CHECKING_SCREEN_CAST_PERMISSION_DIALOG", e);
            return false;
        }
    }
    
    /**
     * 自动点击允许按钮
     */
    private void autoClickAllowButton(AccessibilityEvent event) {
        try {
            Log.d(TAG, "🔧 AUTO_CLICKING_ALLOW_BUTTON");
            
            // 这里需要与AccessibilityKeeperService配合
            // 通过无障碍服务来点击允许按钮
            
            // 发送广播通知AccessibilityKeeperService处理
            Intent intent = new Intent("com.demo.accessibilitykeeper.AUTO_CLICK_ALLOW");
            intent.putExtra("action", "click_allow_button");
            intent.putExtra("dialog_type", "screen_cast_permission");
            sendBroadcast(intent);
            
            Log.d(TAG, "✅ Auto click allow button request sent");
            
        } catch (Exception e) {
            Log.e(TAG, "❌ ERROR_AUTO_CLICKING_ALLOW_BUTTON", e);
        }
    }
    
    /**
     * 检查投屏是否已启用
     */
    public boolean isScreenCastEnabled() {
        return isScreenCastEnabled;
    }
    
    /**
     * 检查自动点击是否已启用
     */
    public boolean isAutoClickEnabled() {
        return isAutoClickEnabled;
    }
    
    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "ScreenCastService destroyed");
        
        // 清理资源
        if (isScreenCastEnabled) {
            disableScreenCast();
        }
    }
    
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}
